<template>
    <el-tabs v-model="editableTabsValue" type="card" class="demo-tabs" closable @tab-remove="removeTab"
        @tab-click="handleTabClick">
        <el-tab-pane v-for="item in editableTabs" :key="item.name" :label="item.title" :name="item.name"
            :closable="item.title !== '首页'">

        </el-tab-pane>
    </el-tabs>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import type { TabPaneName, TabsPaneContext } from 'element-plus'
const route = useRoute()
const router = useRouter()
let tabIndex = 1
// 激活的标签页
const editableTabsValue = ref('1')
// 标签页信息
const editableTabs = ref([
    {
        title: '首页',
        name: '1',
    },
])
// 添加标签页的方法
const addTab = (targetName: string) => {
    const newTabName = `${++tabIndex}`
    editableTabs.value.push({
        title: targetName,
        name: newTabName,
    })
    editableTabsValue.value = newTabName
}
// 移除标签页的方法
const removeTab = (targetName: TabPaneName) => {
    const tabs = editableTabs.value
    let activeName = editableTabsValue.value
    if (activeName === targetName) {
        tabs.forEach((tab, index) => {
            if (tab.name === targetName) {
                const nextTab = tabs[index + 1] || tabs[index - 1]
                if (nextTab) {
                    activeName = nextTab.name
                    // console.log(nextTab) // {title: '操作日志', name: '4'}
                    router.push({ name: nextTab.title })
                }
            }
        })
    }

    editableTabsValue.value = activeName
    editableTabs.value = tabs.filter((tab) => tab.name !== targetName)
}
// 侦听路由变化
watch(route, (val) => {
    // 从标签页信息中查找要添加的标签页是否已存在
    let res = editableTabs.value.find(item => item.title === val.meta.title)
    if (res) {
        // 标签页已存在，激活已存在的标签页
        editableTabsValue.value = res.name
    } else {
        // 标签页不存在，添加新的标签页
        addTab(val.meta.title as string)
    }
}, {
    immediate: true,
    deep: true
})
// 标签页被选中时触发
const handleTabClick = (pane: TabsPaneContext) => {
    // console.log(pane.props) // {name: '1', label: '首页', closable: undefined, disabled: false, lazy: false}
    router.push({ name: pane.props.label })
}
</script>

<style>
.demo-tabs>.el-tabs__content {
    padding: 32px;
    color: #6b778c;
    font-size: 32px;
    font-weight: 600;
}
</style>
